/*
 * @Author: shimmer
 * @Date: 2022-06-15 08:22:19
 * @LastEditors: zhangzhen
 * @LastEditTime: 2022-10-20 08:45:53
 * @Description:
 *
 */

import { extend } from 'umi-request'
import qs from 'qs'

const request = extend({
  // prefix: '/',
  timeout: 30000
})

// 请求前处理
request.interceptors.request.use((url, options) => ({
  url,
  options: {
    ...options,
    headers: {
      'Content-Type': 'application/json;charset=utf-8',
      ...options.headers
    }
  }
}))

/**
 * 响应拦截器
 * code!=200 返回服务器信息
 */
request.interceptors.response.use(async (response) => {
  const data = await response.clone().json()
  // 后端返回code非200情况统一进入错误处理
  if (Number(data.code) !== 200) {
    return Promise.reject(data)
  }
  return response
})

export const get = (url: string) => async (params: any) =>
  request(`${url}${params ? `?${qs.stringify(params)}` : ''}`).then((res) => {
    if (String(res.code) === '200') {
      return res
    }
    return null
  })

export const post = (url: string) => async (params: any) =>
  request.post(url, { params }).then((res) => {
    if (String(res.code) === '200') {
      return res
    }
    return null
  })

export default request
